package com.yfp.client.interceptor;

import com.google.common.util.concurrent.RateLimiter;
import com.yfp.client.annotation.AnonymousAccess;
import com.yfp.client.domain.Client;
import com.yfp.client.generator.TokenGenerator;
import com.yfp.client.service.ClientService;
import com.yfp.client.service.MachineService;
import com.yfp.client.util.RedisKey;
import com.yfp.common.core.exception.ClientAuthException;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.common.core.utils.StringUtils;
import com.yfp.common.core.utils.ip.IpUtils;
import com.yfp.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ClientService clientService;

    @Autowired
    private MachineService machineService;

    // 检查IP+URI是否超过限制
    private static final Map<String, RateLimiter> rateLimiters = new ConcurrentHashMap<>();
    private static final double PERMITS_PER_SECOND = 10;

    public static boolean allowRequest(String ip) {
        RateLimiter rateLimiter = rateLimiters.computeIfAbsent(ip, k -> RateLimiter.create(PERMITS_PER_SECOND));
        return rateLimiter.tryAcquire();
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token

        String token = httpServletRequest.getHeader("Authorization");
        String uri = httpServletRequest.getRequestURI() + httpServletRequest.getMethod();
        String ip = IpUtils.getIpAddr();
        logger.info("IP:{}, URL:{}, method:{}",ip, httpServletRequest.getRequestURI(), httpServletRequest.getMethod());
        // 检查IP+URI是否超过限制
        if (!allowRequest(ip+uri)) {
            throw new ServiceException("请稍后重试！");
        }

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有@AnonymousAccess注释，有则跳过认证
        if (method.isAnnotationPresent(AnonymousAccess.class)) {
            AnonymousAccess anonymousAccess = method.getAnnotation(AnonymousAccess.class);
            if (anonymousAccess.required()) {
                return true;
            }
        }

        // 执行认证
        if (StringUtils.isEmpty(token)) {
            throw new ClientAuthException("Authorization不能为空");
        }

        // 验证token
        boolean tokanVaildate = TokenGenerator.validateToken(token);
        if (tokanVaildate){
            Claims claims = TokenGenerator.parseJWT(token);
            log.info("claims:{}", claims);
            String clientId = claims.get("clientId").toString();
            Client client = redisService.getCacheObject(MessageFormat.format(RedisKey.LOGIN, clientId) );
            if (Objects.isNull(client)){
                client = clientService.getById(clientId);
                // 缓存当前用户信息，过期时间一小时
                redisService.setCacheObject(MessageFormat.format(RedisKey.LOGIN, clientId), client, 1L, TimeUnit.HOURS);
            }
        } else {
            throw new ClientAuthException("Authorization无效");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
